package com.itlin.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itlin.bean.Employee;
import com.itlin.bean.PageParam;
import com.itlin.dao.EmployeeDao;
import com.itlin.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;



/**
 * @author 所谓伊人
 * @date 2022/3/19 - 17:53
 */
@Transactional
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeDao dao;

    @Override
    public Employee login(Employee employee) {

        // 1. 构建条件对象
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();

        // 2. 追加条件==>姓名
        qw.eq(Employee::getUsername, employee.getUsername());

        // 3. 不能直接拿明文去查询数据库，这样查不到数据库的
        // 先加密密码
        String md5Passwword = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());

        //4. 追加查询条件==>密码
        qw.eq(Employee::getPassword,md5Passwword);

        //5. 执行查询
        return dao.selectOne(qw);
    }

    @Override
    public int add(Employee employee) {

        return dao.insert(employee);
    }

    @Override
    public IPage<Employee> findPage(PageParam pageParam) {

        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();

        qw.like(pageParam.getName() != null, Employee::getName,pageParam.getName());

        Page<Employee> page = new Page<>(pageParam.getPage(), pageParam.getPageSize());

        return dao.selectPage(page, qw);
    }

    @Override
    public int update(Employee employee) {
        return dao.updateById(employee);
    }
}
